package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    private Socket socket =null;
    public TcpEchoClient(String serverIp,int serverPort) throws IOException {
        //此处可以把这里的ip和port直接传给socket对象
        //由于tcp是有连接的,因此socket里面就会保存号这俩信息
        //因此此处TcpEchoClient类就不必保存了
        socket = new Socket(serverIp,serverPort);//这里的new操作就触发了和服务器之间的建立连接的操作
    }
    public void start() {
        System.out.println("客户端启动!");
        try (InputStream inputStream = socket.getInputStream();
             OutputStream outputStream = socket.getOutputStream()){
            Scanner scannerConsole = new Scanner(System.in);
            Scanner scannerNetwork = new Scanner(inputStream);
            PrintWriter writer = new PrintWriter(outputStream);

            while (true) {
                //这里的流程和UDP一样
                //1.从控制台读取输入的字符串
                System.out.print("->");
                if(!scannerConsole.hasNext()) {
                    break;
                }
                String request = scannerConsole.next();
                //2.把请求发给服务器
                //这里和服务器的 scanner.next呼应的
                writer.println(request);//这里的缓冲区把多次IO合并成一次了,如果发送的很少,缓冲区没满,则发送不出去,可以手动冲刷缓冲区来解决该问题
                //通过这个flush()注定刷新缓冲区,确保数据真的发送出去了
                writer.flush();
                //3.从服务器读取响应,这里和服务器返回响应的逻辑对应
                String response = scannerNetwork.next();
                //4.把响应显示出来
                System.out.println(response);
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient client = new TcpEchoClient("127.0.0.1",9090);
        client.start();
    }
}
